package com.eduagent.xwqeduagent.controller;

import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.constant.VoiceRecognitionConstant;
import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.model.BusinessParam;
import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.service.VoiceRecognitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 流式语音识别控制器
 */
@RestController
@RequestMapping("/voice-recognition")
@Slf4j
public class VoiceRecognitionController {

    @Autowired
    private VoiceRecognitionService voiceRecognitionService;
    
    /**
     * 初始化方法，设置API凭证
     */
    @PostConstruct
    public void init() {
        // 设置API凭证，实际应通过配置文件或环境变量设置
        VoiceRecognitionConstant.APP_ID = "637d1630";
        VoiceRecognitionConstant.API_KEY = "8bd0514cb66802c719bbf34a908a0119";
        VoiceRecognitionConstant.API_SECRET = "NzUyY2Y3OTYwYjAyMGExODc5OTM1ZGZl";
    }

    /**
     * 上传音频进行识别
     * 
     * @param file 音频文件
     * @param language 语言（zh_cn-中文，en_us-英文）
     * @param domain 领域（iat-通用，medical-医疗）
     * @param accent 方言（mandarin-普通话）
     * @param enablePunctuation 是否添加标点符号（默认为true）
     * @param enableWordSegmentation 是否进行分词（默认为false）
     * @return 识别结果
     */
    @PostMapping("/recognize")
    public ResponseEntity<Map<String, Object>> recognizeSpeech(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "language", defaultValue = "zh_cn") String language,
            @RequestParam(value = "domain", defaultValue = "iat") String domain,
            @RequestParam(value = "accent", defaultValue = "mandarin") String accent,
            @RequestParam(value = "enablePunctuation", defaultValue = "true") boolean enablePunctuation,
            @RequestParam(value = "enableWordSegmentation", defaultValue = "false") boolean enableWordSegmentation) {
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("音频文件不能为空"));
            }
            
            // 检查文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(createErrorResponse("音频文件大小超过10MB限制"));
            }
            
            // 读取音频数据
            byte[] audioData = file.getBytes();
            
            // 构建业务参数
            BusinessParam businessParam = BusinessParam.builder()
                    .language(language)
                    .domain(domain)
                    .accent(accent)
                    .ptt(enablePunctuation ? 1 : 0)
                    .build();
            
            // 执行语音识别（同步方法）
            String result = voiceRecognitionService.recognizeSpeech(audioData, businessParam);
            
            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("text", result);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("语音识别失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("语音识别失败: " + e.getMessage()));
        }
    }
    
    /**
     * 异步上传音频进行识别
     * 
     * @param file 音频文件
     * @param language 语言（zh_cn-中文，en_us-英文）
     * @param domain 领域（iat-通用，medical-医疗）
     * @param accent 方言（mandarin-普通话）
     * @param enablePunctuation 是否添加标点符号（默认为true）
     * @return 任务ID
     */
    @PostMapping("/recognize/async")
    public ResponseEntity<Map<String, Object>> recognizeSpeechAsync(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "language", defaultValue = "zh_cn") String language,
            @RequestParam(value = "domain", defaultValue = "iat") String domain,
            @RequestParam(value = "accent", defaultValue = "mandarin") String accent,
            @RequestParam(value = "enablePunctuation", defaultValue = "true") boolean enablePunctuation) {
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("音频文件不能为空"));
            }
            
            // 检查文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(createErrorResponse("音频文件大小超过10MB限制"));
            }
            
            // 读取音频数据
            byte[] audioData = file.getBytes();
            
            // 生成任务ID
            String taskId = java.util.UUID.randomUUID().toString();
            
            // 构建业务参数
            BusinessParam businessParam = BusinessParam.builder()
                    .language(language)
                    .domain(domain)
                    .accent(accent)
                    .ptt(enablePunctuation ? 1 : 0)
                    .dwa("wpgs") // 开启动态修正
                    .build();
            
            // 异步执行语音识别
            CompletableFuture.runAsync(() -> {
                try {
                    voiceRecognitionService.recognizeSpeechAsync(audioData, businessParam,
                            new VoiceRecognitionService.RecognitionCallback() {
                                @Override
                                public void onSuccess(String result) {
                                    log.info("Task {} 识别成功: {}", taskId, result);
                                }
                                
                                @Override
                                public void onError(int errorCode, String errorMessage) {
                                    log.error("Task {} 识别失败: {}, 错误码: {}", taskId, errorMessage, errorCode);
                                }
                                
                                @Override
                                public void onPartialResult(String result, boolean isLast) {
                                    log.debug("Task {} 实时识别结果: {}", taskId, result);
                                }
                            });
                } catch (Exception e) {
                    log.error("Task {} 识别失败", taskId, e);
                }
            });
            
            // 返回任务ID
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("taskId", taskId);
            response.put("message", "语音识别任务已提交，请通过taskId查询结果");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("提交语音识别任务失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("提交语音识别任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建错误响应
     * 
     * @param message 错误信息
     * @return 错误响应Map
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
} 